package com.qy127.javaweb.controller;

import com.alibaba.fastjson.JSON;
import com.qy127.javaweb.dao.impl.StaffDaoImpl;
import com.qy127.javaweb.entity.Staff;
import com.qy127.javaweb.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@WebServlet("/sta/*")//设置可以使用所有请求
public class StaffServlet extends HttpServlet {
    StaffDaoImpl staffDao = new StaffDaoImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();//获取请求uri
        int i = uri.lastIndexOf("/");
        String s = uri.substring(i + 1);
        switch (s){
            case "getAllsta":
                getAllsta(req,resp);
                break;
            case "addStaff":
                addStaff(req,resp);
            case "delStaff":
                delStaff(req,resp);
            default:
                break;
        }
    }
    protected void getAllsta(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //数据操作

        List<Map<String, Object>> staff = staffDao.getStaff();
        int i = staff.size();
        Result result = new Result(i, staff);
        String s = JSON.toJSONString(result);
        PrintWriter writer = resp.getWriter();
        writer.write(s);
    }
    protected void addStaff(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求数据
        int staffId = Integer.parseInt(req.getParameter("staffId"));
        String staffName = req.getParameter("staffName");
        String password = req.getParameter("password");
        String phone = req.getParameter("phone");
        String idCard = req.getParameter("idCard");
        String address = req.getParameter("address");
        Staff staff = new Staff(null, staffId, staffName, password, phone, idCard, address);

        //数据操作
        int i = staffDao.insertStaff(staff);
        if(i>0){
            req.setAttribute("msg","新增成功");
        }else {
            req.setAttribute("msg","新增失败");
        }
        req.getRequestDispatcher("/addStaff.jsp").forward(req,resp);
    }
    protected void delStaff(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        int i = staffDao.deleteStaff(Integer.parseInt(id));
//        System.out.println(id);
            if(i>0){
                getAllsta(req,resp);
                req.getRequestDispatcher("/staff.jsp").forward(req,resp);
            }

    }
}
